using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.Dto.HumanResources.HumanResourceManagement;
using ERP.EntityFrameworkCore;
using ERP.ERPModels.Production.MasterData; // 确保这是正确的命名空间
using ERP.HumanResources.HumanResourceManagement.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace ERP.Web.Controllers.Production
{
    public class SupplierController : Controller
    {
        private readonly ERPDbContext _dbContext;

        public SupplierController(ERPDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 新增供应商页面
        /// </summary>
        public IActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 编辑供应商页面
        /// </summary>
        public IActionResult Edit()
        {
            return View();
        }

        /// <summary>
        /// 获取供应商详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSupplierById(int id)
        {
            try
            {
                Console.WriteLine($"DEBUG: 尝试获取供应商ID: {id}");
                
                var supplier = await _dbContext.Supplier
                    .FirstOrDefaultAsync(x => x.Id == id);

                if (supplier == null)
                {
                    Console.WriteLine($"DEBUG: 未找到供应商ID: {id}");
                    return Json(new { code = 1, msg = "未找到供应商信息" });
                }

                Console.WriteLine($"DEBUG: 成功获取供应商 - 编码: {supplier.SupplierCode}, 名称: {supplier.SupplierName}");
                
                // 检查属性名称是否一致
                var json = JsonConvert.SerializeObject(supplier);
                Console.WriteLine($"DEBUG: 供应商数据: {json}");

                // 创建明确的响应对象，确保字段名与前端期望一致
                var response = new
                {
                    id = supplier.Id,
                    supplierCode = supplier.SupplierCode,
                    supplierName = supplier.SupplierName,
                    supplierGrade = supplier.SupplierGrade,
                    supplierScore = supplier.SupplierScore,
                    isNo = supplier.IsNo,
                    supplierPhone = supplier.SupplierPhone,
                    supplierAdress = supplier.SupplierAdress,
                    context = supplier.Context
                };
                
                return Json(new { 
                    code = 0, 
                    msg = "success", 
                    data = response 
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DEBUG: 异常: {ex.Message}");
                return Json(new { code = 1, msg = $"获取供应商信息失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 更新供应商信息
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateSupplier(UpdSupplierDto supplierDto)
        {
            try
            {
                Console.WriteLine($"DEBUG: 接收到的供应商DTO: {JsonConvert.SerializeObject(supplierDto)}");
                Console.WriteLine($"DEBUG: 供应商ID: {supplierDto?.Id}");
                
                if (supplierDto == null)
                {
                    Console.WriteLine("DEBUG: 供应商DTO为空");
                    return Json(new { code = 1, msg = "提交的数据格式不正确" });
                }
                
                if (supplierDto.Id <= 0)
                {
                    Console.WriteLine($"DEBUG: 无效的供应商ID: {supplierDto.Id}");
                    return Json(new { code = 1, msg = "无效的供应商ID" });
                }
                
                // 查找现有供应商
                var supplier = await _dbContext.Supplier.FindAsync(supplierDto.Id);
                if (supplier == null)
                {
                    Console.WriteLine($"DEBUG: 未找到ID为{supplierDto.Id}的供应商");
                    return Json(new { code = 1, msg = "未找到供应商信息" });
                }

                Console.WriteLine($"DEBUG: 找到供应商 - ID:{supplier.Id}, 编码:{supplier.SupplierCode}, 名称:{supplier.SupplierName}");

                // 更新属性（保留原编码，不允许修改）
                supplier.SupplierName = supplierDto.SupplierName;
                supplier.SupplierGrade = supplierDto.SupplierGrade;
                supplier.SupplierScore = supplierDto.SupplierScore;
                supplier.SupplierPhone = supplierDto.SupplierPhone;
                supplier.IsNo = supplierDto.IsNo;
                supplier.SupplierAdress = supplierDto.SupplierAdress;
                supplier.Context = supplierDto.Context;

                // 保存更改
                _dbContext.Supplier.Update(supplier);
                await _dbContext.SaveChangesAsync();

                Console.WriteLine("DEBUG: 供应商数据更新成功");
                return Json(new { code = 0, msg = "更新成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DEBUG: 更新失败 - {ex.Message}");
                Console.WriteLine($"DEBUG: 详细错误 - {ex.StackTrace}");
                return Json(new { code = 1, msg = $"更新失败: {ex.Message}" });
            }
        }
        
        // 辅助方法：从字典中获取字符串值，尝试多种可能的键名
        private string GetStringValue(Dictionary<string, object> dict, params string[] keys)
        {
            foreach (var key in keys)
            {
                if (dict.ContainsKey(key) && dict[key] != null)
                {
                    return dict[key].ToString();
                }
            }
            return string.Empty;
        }
        
        // 辅助方法：从字典中获取整数值，尝试多种可能的键名
        private int GetIntValue(Dictionary<string, object> dict, params string[] keys)
        {
            foreach (var key in keys)
            {
                if (dict.ContainsKey(key) && dict[key] != null)
                {
                    if (int.TryParse(dict[key].ToString(), out int result))
                    {
                        return result;
                    }
                }
            }
            return 0;
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteSupplier(int id)
        {
            try
            {
                var supplier = await _dbContext.Supplier.FindAsync(id);
                if (supplier == null)
                {
                    return Json(new { code = 1, msg = "供应商不存在" });
                }

                _dbContext.Supplier.Remove(supplier);
                await _dbContext.SaveChangesAsync();
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除供应商
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                var suppliers = await _dbContext.Supplier
                    .Where(x => ids.Contains(x.Id))
                    .ToListAsync();

                if (suppliers.Count == 0)
                {
                    return Json(new { code = 1, msg = "未找到要删除的供应商" });
                }

                _dbContext.Supplier.RemoveRange(suppliers);
                await _dbContext.SaveChangesAsync();
                return Json(new { code = 0, msg = "批量删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"批量删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取面试管理分页列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSupplierList(GetSupplierManagementDto getSupplierDto)
        {
            // 1. 获取基础查询
            var query = _dbContext.Supplier.AsQueryable();

       
            // 2. 应用筛选条件
            if (!string.IsNullOrWhiteSpace(getSupplierDto.SupplierCode))
            {
                query = query.Where(x => x.SupplierCode.Contains(getSupplierDto.SupplierCode));
            }

            if (!string.IsNullOrWhiteSpace(getSupplierDto.SupplierName))
            {
                query = query.Where(x => x.SupplierName.Contains(getSupplierDto.SupplierName));
            }
            
            // 修改条件判断逻辑，值为2时表示查询所有
            if (getSupplierDto.IsNo == 0 || getSupplierDto.IsNo == 1)
            {
                query = query.Where(x => x.IsNo == getSupplierDto.IsNo);
            }
            // IsNo为2或其他值时不添加筛选条件，查询所有数据

            // 3. 计算总记录数
            var totalCount = await query.CountAsync();

            // 4. 执行分页查询
            var items = await query
                .OrderByDescending(x => x.Id)
                .Skip((getSupplierDto.pageIndex - 1) * getSupplierDto.pageSize)
                .Take(getSupplierDto.pageSize)
                .ToListAsync();
                
            // 输出调试信息
            Console.WriteLine($"总记录数: {totalCount}, 当前页数据量: {items.Count}");

            // 5. 构建返回结果 - 转换为统一格式的数据
            var result = items.Select(item => new {
                id = item.Id, // 确保使用小写id作为主键字段
                supplierCode = item.SupplierCode,
                supplierName = item.SupplierName,
                supplierGrade = item.SupplierGrade,
                supplierScore = item.SupplierScore,
                supplierPhone = item.SupplierPhone,
                isNo = item.IsNo,
                supplierAdress = item.SupplierAdress,
                context = item.Context
            }).ToList();

            return Json(new
            {
                code = 0,
                msg = "success",
                count = totalCount,
                data = result
            });
        }

        /// <summary>
        /// 生成供应商编码
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateSupplierCode()
        {
            try
            {
                // 获取当前最大的编码
                var maxCode = await _dbContext.Supplier
                    .OrderByDescending(s => s.SupplierCode)
                    .FirstOrDefaultAsync(s => s.SupplierCode.StartsWith("V"));

                string newCode = "V00001";
                
                if (maxCode != null)
                {
                    // 提取数字部分
                    if (int.TryParse(maxCode.SupplierCode.Substring(1), out int codeNum))
                    {
                        codeNum++;
                        newCode = $"V{codeNum:D5}";
                    }
                }

                return Json(new { code = 0, msg = "success", data = newCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"生成编码失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 添加供应商
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddSupplier([FromBody] Supplier supplierDto)
        {
            try
            {
                // 检查编码是否已存在
                var existingSupplier = await _dbContext.Supplier
                    .FirstOrDefaultAsync(x => x.SupplierCode == supplierDto.SupplierCode);

                if (existingSupplier != null)
                {
                    return Json(new { code = 1, msg = $"供应商编码 {supplierDto.SupplierCode} 已存在" });
                }

                // 设置默认值
                if (supplierDto.SupplierScore <= 0)
                {
                    supplierDto.SupplierScore = 0;
                }

                // 添加到数据库
                await _dbContext.Supplier.AddAsync(supplierDto);
                await _dbContext.SaveChangesAsync();

                return Json(new { code = 0, msg = "添加成功", data = supplierDto });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"添加失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 更新供应商信息 - 强类型模型绑定方法
        /// </summary>
        [HttpPost("UpdateSupplierModel")]
        public async Task<IActionResult> UpdateSupplierModel([FromBody] Supplier supplierDto)
        {
            try
            {
                // 调试日志
                Console.WriteLine($"DEBUG: 接收到的更新请求数据: {JsonConvert.SerializeObject(supplierDto)}");
                Console.WriteLine($"DEBUG: ID值: {supplierDto.Id}");
                
                if (supplierDto.Id <= 0)
                {
                    Console.WriteLine("DEBUG: 无效的供应商ID，可能数据绑定失败");
                    return Json(new { code = 1, msg = "无效的供应商ID" });
                }
                
                // 查找现有供应商
                var supplier = await _dbContext.Supplier.FindAsync(supplierDto.Id);
                if (supplier == null)
                {
                    Console.WriteLine($"DEBUG: 未找到ID为{supplierDto.Id}的供应商");
                    return Json(new { code = 1, msg = "未找到供应商信息" });
                }

                Console.WriteLine($"DEBUG: 找到供应商 - ID:{supplier.Id}, 编码:{supplier.SupplierCode}, 名称:{supplier.SupplierName}");

                // 更新属性（保留原编码，不允许修改）
                supplier.SupplierName = supplierDto.SupplierName;
                supplier.SupplierGrade = supplierDto.SupplierGrade;
                supplier.SupplierScore = supplierDto.SupplierScore;
                supplier.SupplierPhone = supplierDto.SupplierPhone;
                supplier.IsNo = supplierDto.IsNo;
                supplier.SupplierAdress = supplierDto.SupplierAdress;
                supplier.Context = supplierDto.Context;

                // 保存更改
                _dbContext.Supplier.Update(supplier);
                await _dbContext.SaveChangesAsync();

                Console.WriteLine("DEBUG: 供应商数据更新成功");
                return Json(new { code = 0, msg = "更新成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DEBUG: 更新失败 - {ex.Message}");
                Console.WriteLine($"DEBUG: 详细错误 - {ex.StackTrace}");
                return Json(new { code = 1, msg = $"更新失败: {ex.Message}" });
            }
        }
    }
} 